<?php
/**
 * 分拣配货API
 * User: rui
 * Email: poptser@foxmail.com
 * Date: 2016/10/10
 * Time: 14:59
 */

namespace YMApi\Controller;
use Think\Controller;
use Think\Exception;
use Think\Model;
use Common\Api\Ali_ossApi;

class SortingController extends AppController
{
    public function _initialize($apptoken = '', $apptime = '', $check_uid = false, $session_id = '', $check_sign = true)
    {
        parent::_initialize($apptoken, $apptime, $check_uid, $session_id, false);

        $warehouse_personnel=M('warehouse_personnel');
        $user_id=I('post.user_id','intval');
        $wprow=$warehouse_personnel->field('position,wid,longitude,latitude,status')->where(array('uid'=>$user_id,'position'=>1))->find();
        if(!$wprow){
            //returnApiError("无此操作权限");
        }
    }

    /**
     * 根据用户ID获取仓库ID
     * rui poptser@foxmail.com 2016-10-10 10:09:19
     * @param $user_id
     */
    private function get_user_wid_identity($user_id){
        //$user_wid = S("swid_".$user_id);
        if(empty($user_wid)){
            $user_wid = M("warehouse_personnel")->where(array("uid"=>$user_id))->getField("wid");
            //S("swid_".$user_id,$user_wid);
        }
        return $user_wid;
    }

    /**
     * 获取地址信息
     * rui poptser@foxmail.com 2016-10-11 09:30:20
     * @param $country
     * @param $province
     * @param $city
     * @param $district
     * @return string
     */
    private function get_address_desc($country, $province, $city, $district){
        $country_name=A("Distribution")->get_region_name($country);
        $province_name=A("Distribution")->get_region_name($province);
        $city_name=A("Distribution")->get_region_name($city);
        $district_name=A("Distribution")->get_region_name($district);
        return $country_name.$province_name.$city_name.$district_name;
    }

    /**
     * 检查提交账号是否为仓库账号
     * rui poptser@foxmail.com 2016-10-11 10:09:19
     * @param $user_id
     */
    private function check_user($user_id){
        $wp=A("Distribution")->check_warehouse_personnel($user_id);
        if(!$wp){
            returnApiError('无此用户/禁用');
            exit();
        }
    }


    /**
     * 修改订单为配货中
     * rui poptser@foxmail.com 2016-10-11 10:09:19
     * @param $user_id
     * @param $order_id
     */
    private function deploy_order_action($user_id,$order_id,$wid,$is_r=false){

        $where = "order_id = ".$order_id." AND wid = ".$wid;
        $where = $where." AND sorting_id = 0 AND shipping_status in(0,3) AND order_status !=2 AND pay_status in(2,3)";
        $where = $where." AND (is_presell = 0 OR (is_presell = 1 AND buckle_inventory = 1))";

        $data['sorting_id'] = $user_id;
        $data['shipping_status'] = 3;   //修改为配货中
        if($is_r){
            $data['is_random'] = 1;
        }
        $result = M("order_info")->where($where)->save($data);    //修改订单信息表中的  sorting_id  开始配货


        if($result){
            //修改成功，写入日志
            $order_info = M("order_info")->where("order_id = ".$order_id)->find();
            $a=array(
                'order_id'=>$order_id,
                'user_id'=>$user_id,
                'order_status'=>$order_info['order_status'],
                'shipping_status'=>3,
                'pay_status'=>$order_info['pay_status'],
                'action_note'=>'配货中'
            );

            A("Distribution")->record_diliveryman_log($a);//记录配送员操作日志
            return true;
        }else{
            $order_info = M("order_info")->where("order_id = ".$order_id)->find();

            if($order_info['wid']!=$wid) returnApiError("非本仓库订单,此单属于仓库:{$order_info['wid']},{$order_info['order_sn']}");

            if($order_info['sorting_id']!=0) returnApiError("已在配货中{$order_info['order_sn']}");

            if($order_info['shipping_status']!=0 && $order_info['shipping_status']!=3) returnApiError("订单不在未发货状态{$order_info['order_sn']}");

            if($order_info['order_status']==2) returnApiError("订单已被取消{$order_info['order_sn']}");

            if($order_info['pay_status']!=2 && $order_info['pay_status']!=3) returnApiError("订单还未支付{$order_info['order_sn']}");

            if($order_info['is_presell'] ==1 && $order_info['buckle_inventory'] ==0 ) returnApiError("预售单无法配货{$order_info['order_sn']}");

            return false;
        }
    }

    /**
     * 修改订单为配送中
     * rui poptser@foxmail.com 2016-11-28 17:52:54
     * @param $user_id
     * @param $order_id
     * @param $wid
     */
    private function distribute_order_action($user_id, $order_id, $wid,$is_r = false){
        //$this->distribute_order_action($wp_userid, $result['order_id'], $wid, true);

        if(!isset($user_id) || !isset($order_id)){
            returnApiError('参数错误');
        }
        $where['order_id']=$order_id;
        $where['shipping_status']=5;
        $where['order_status']=array("neq",2);
        $where['pay_status']=array("in","2,3");
        //$where['wid']=$wid;

        $list=M('order_info')->field('order_id,order_sn,user_id,order_status,shipping_status,pay_status,mobile,consignee,best_time,best_time_start,pay_time,is_presell,wid')->where($where)->find();
        if($list['order_id']){
            try {
                $data['order_status']=5;
                $data['shipping_status']=1;
                $data['shipping_time']=gmtime();
                $data['wp_userid'] = $user_id;
                if($is_r){
                    //随机获取的订单 标记
                    $data['is_random_ps'] = 1;
                }
                $id=M('order_info')->where($where)->save($data);
                if($id!=false){
                    $a=array(
                        'order_id'=>$list['order_id'],
                        'user_id'=>$user_id,
                        'order_status'=>5,
                        'shipping_status'=>1,
                        'pay_status'=>$list['pay_status'],
                        'action_note'=>'发货中'
                    );
                    A("Distribution")->record_diliveryman_log($a);//记录配送员操作日志

                    $remark['phone'] = M('warehouse_personnel')->where(array('uid'=>$user_id))->getField('phone');


                    $remark['best_time'] = date("Y-m-d",$list['best_time_start']).' '.date("H:i:s",$list['best_time_start']).'-'.date("H:i:s",$list['best_time']);

                    A("Smsapi")->send_message_api('shipping_start_notice',$list['mobile'],$list['consignee'],0,$list['order_sn'],0,$list['user_id'],$remark);
                    returnApiSuccess(array('id'=>$id),'配送订单成功');
                }else{
                    returnApiError('配送订单失败');
                }
            }catch(Exception $e){
                returnApiErrorExample($e->getMessage());
            }
        }else{
            returnApiError('无此订单/订单不在配货完成状态');
        }
    }

    /**
     * TODO 订单下商品列表（返回用）
     * rui poptser@foxmail.com 2016-11-22 15:32:01
     */
    public function sh_goods_list($order_id,$wid){
        $rui_goods_list = array();
        $goods_list = $this->get_goods_list_real($order_id);
        //dump($goods_list);
        if(count($goods_list)>0){
            foreach ($goods_list as $key=>$value){
                $goods_data = M("goods")->where(array("goods_id"=>$value['goods_id']))->find();
                $goods_lists['count'] = $value['real_num'];     //数量
                //dump($value['giving']);

                $goods_lists['name'] = $value['goods_name'];    //商品名
                switch ($value['giving']){
                    case 1:
                        $goods_lists[$key]['goods_name'] .=" [ 赠品 ] ";
                        break;
                    case 2:
                        $goods_lists[$key]['goods_name'] .=" [ 换购 ] ";
                        break;
                    case 3:
                        $goods_lists[$key]['goods_name'] .=" [ 抢购 ] ";
                        break;
                    case 4:
                        $goods_lists[$key]['goods_name'] .=" [ 促销 ] ";
                        break;
                }


                $goods_lists['price'] = $value['goods_price'];  //价格
                $goods_lists['act_id'] = $value['act_id'];  //活动ID
                $goods_lists['giving'] = $value['giving'];  //  商品类型
                $goods_lists['id'] = $value['goods_id'];        //商品ID
                $goods_lists['shop_remark'] = $goods_data['seller_note'];    //商家备注
                $goods_lists['goods_number'] = $value['goods_sn'];      //货号
                $store_count = M("goods_storage")->where("goods_id =".$value['goods_id']." AND wid = ".$wid)->find();
                $goods_lists['store_count'] = "实：".$store_count['practical_num']." 冻：".$store_count['freeze_num']; //库存
                $goods_lists['goods_category'] = M("category")->where(array("cat_id"=>$value['cat_id']))->getField('cat_name'); //分类名

                //货架信息
                $model = M();
                $sql = "SELECT sh.*,sc.name AS shelf_tag,sl.name AS shelf_type,wh.name AS shelf_store,sg.sh_floor AS putaway_row,
                sh.shelves_sn AS shelf_num
                FROM sdx_shelves AS sh,sdx_shelves_cat AS sc,sdx_shelves_class AS sl ,sdx_warehouse AS wh,sdx_shelves_goods AS sg
                WHERE 
                sh.category_id = sc.id AND sh.class_id = sl.id AND sh.wid =  wh.id AND sg.sh_id = sh.id AND sh.wid = '".$wid."' 
                AND sg.goods_sn = '".$value['goods_sn']."'";
                $goods_shelves = $model->query($sql);
                if($goods_shelves){
                    $goods_lists['shelf_info'] = "";
                    foreach ($goods_shelves as $vaule){
                        $goods_lists['shelf_info'] .= $vaule['shelf_tag']."->".$vaule['shelf_type']."[ ".$vaule['shelf_num']."-".$vaule['putaway_row']." ]\n";
                    }
                    $goods_lists['shelf_sort'] = $goods_shelves[0]['sort'];
                }else{
                    $goods_lists['shelf_info'] = "无货架信息";
                    $goods_lists['shelf_sort'] = 999999;
                }

                $goods_lists['goods_img'] = $goods_data['goods_img'];    //商品图片
                $goods_lists['original_img'] = $goods_data['original_img']; //商品缩略图

                $goods_lists['price_member'] = D('goods')->get_vip_price_for_all($value['goods_id'],1); //注册会员价
                $goods_lists['price_vip']    = D('goods')->get_vip_price_for_all($value['goods_id'],2); //VIP会员价



                array_push($rui_goods_list,$goods_lists);
            }
            return $rui_goods_list;
        }else{
            return false;
        }
    }

    /**
     * TODO 订单下退款商品列表（返回用）
     * @param $order_id
     * @param $wid
     * @return array|bool
     */
    public function re_goods_list($order_id, $wid){
        $goods_list = $this->get_refund_goods_list($order_id);

        if(count($goods_list)>0){
            $rui_goods_list = array();
            foreach ($goods_list as $key=>$value){
                $goods_data = M("goods")->where(array("goods_id"=>$value['goods_id']))->find();
                $goods_lists['count'] = $value['refund_number'];
                $goods_lists['name'] = $value['goods_name'];
                switch ($value['giving']){
                    case 1:
                        $goods_lists[$key]['goods_name'] .=" [ 赠品 ] ";
                        break;
                    case 2:
                        $goods_lists[$key]['goods_name'] .=" [ 换购 ] ";
                        break;
                    case 3:
                        $goods_lists[$key]['goods_name'] .=" [ 抢购 ] ";
                        break;
                    case 4:
                        $goods_lists[$key]['goods_name'] .=" [ 促销 ] ";
                        break;
                }
                $goods_lists['giving'] = $value['giving'];  //  商品类型
                $goods_lists['price'] = M("goods")->where(array("goods_id"=>$value['goods_id']))->getField('shop_price');
                $goods_lists['id'] = $value['goods_id'];
                $goods_lists['shop_remark'] = M("goods")->where(array("goods_id"=>$value['goods_id']))->getField('seller_note');    //商家备注
                $goods_lists['goods_number'] = $value['goods_sn'];
                $store_count = M("goods_storage")->where("goods_id =".$value['goods_id']." AND wid = ".$wid)->find();
                $goods_lists['store_count'] = "实：".$store_count['practical_num']." 冻：".$store_count['freeze_num'];
                $goods_lists['goods_category'] = M("category")->where(array("cat_id"=>$value['cat_id']))->getField('cat_name');

                //货架信息
                $model = M();
                $sql = "SELECT sh.*,sc.name AS shelf_tag,sl.name AS shelf_type,wh.name AS shelf_store,sg.sh_floor AS putaway_row,
                sh.shelves_sn AS shelf_num
                FROM sdx_shelves AS sh,sdx_shelves_cat AS sc,sdx_shelves_class AS sl ,sdx_warehouse AS wh,sdx_shelves_goods AS sg
                WHERE 
                sh.category_id = sc.id AND sh.class_id = sl.id AND sh.wid =  wh.id AND sg.sh_id = sh.id
                AND sg.goods_sn = '".$value['goods_sn']."'";
                $goods_shelves = $model->query($sql);
                if($goods_shelves){
                    $goods_lists['shelf_info'] = "";
                    foreach ($goods_shelves as $vaule){
                        $goods_lists['shelf_info'] .= $vaule['shelf_tag']."->".$vaule['shelf_type']."[ ".$vaule['shelf_num']."-".$vaule['putaway_row']." ]\n";
                    }
                }else{
                    $goods_lists['shelf_info'] = "无货架信息";
                }
                $goods_lists['goods_img'] = $goods_data['goods_img'];    //商品图片
                $goods_lists['original_img'] = $goods_data['original_img']; //商品缩略图

                $goods_lists['price_member'] = D('goods')->get_vip_price_for_all($value['goods_id'],1); //注册会员价
                $goods_lists['price_vip']    = D('goods')->get_vip_price_for_all($value['goods_id'],2); //VIP会员价

                array_push($rui_goods_list,$goods_lists);
            }
            return $rui_goods_list;
        }else{
            return false;
        }
    }

    /**
     * TODO 获取订单详情
     * @param $result
     * @return mixed
     */
    public function get_order_info($result){
        $result['address'] = $this->get_address_desc($result['country'], $result['province'], $result['city'], $result['district']) . $result['address'] . $result['sign_building'] . $result['address_name'];
        $result['order_time'] = local_date('Y-m-d H:i:s', $result['order_time']);
        $deploy_info = A("Distribution")->get_admin_user_name($result['sorting_id']);
        $distribute_info = A("Distribution")->get_admin_user_name($result['wp_userid']);
        $result['deploy_name'] = $deploy_info['user_name']; //配货员姓名
        $result['deploy_phone'] = $deploy_info['phone']; //配货员手机号码
        $result['distribute_name'] = $distribute_info['user_name']; //配送员姓名
        $result['distribute_phone'] = $distribute_info['phone']; //配送员手机号码
        $result['order_remark']=$result['postscript']; //订单备注
        $result['weight']=$this->get_order_weight($result['order_id']); //订单重量
        $result['order_want_time']=date('Y-m-d H:i:s',$result['best_time_start'])."\n".date('Y-m-d H:i:s',$result['best_time']); //预期送达时间
        $result['order_area']=M("warehouse_deliver_region")->where(array("id"=>$result['wdr_id']))->getField('name'); //配货区域
        $result['order_store']=M("warehouse")->where(array("id"=>$result['wid']))->getField('name'); //配货区域
        return $result;
    }

    /**
     * TODO 获取订单重量
     * @param $order_id
     * @return int
     */
    public function get_order_weight($order_id){
        $order_weight = 0;
        $goods_list = $this->get_goods_list_real($order_id);
        foreach ($goods_list as $value){
            $goods_weight = M("goods")->where(array("goods_id"=>$value['goods_id']))->getField('goods_weight');
            $one_good_weight = $goods_weight*$value['real_num'];
            $order_weight +=$one_good_weight;
        }
        return $order_weight;   //返回本订单总量（单位KG）
    }


    /**
     * 配货中列表
     * rui poptser@foxmail.com 2016-10-10 16:10:29
     */
    // TODO 配货中列表 deploy_list
    public function deploy_list(){
        $user_id=I('post.user_id','intval');
        if(!isset($user_id)){
            returnApiError('参数错误');
        }
        $this->check_user($user_id);
        $wid = $this->get_user_wid_identity($user_id);
        $page=I('post.page','intval');
        $where['sorting_id']=$user_id;
        $where['pay_status']=array('in','2,3');
        $where['order_status']= array('neq',2);
        $where['shipping_status']=3;	//备货中
        $where['wid']=$wid;

        $group_order = M("sorting_order_group")->where("state = 0 AND user_id = ".$user_id)->getField("order_id",true);

        $group_order_array = array();

        foreach ($group_order as $value){
            $value = array_filter(array_unique(explode(",",$value)));

            array_merge($group_order_array,$value);
        }


        if(count($group_order_array)>0){
            $where['order_id'] = array('not in',$group_order_array);
        }


        $where_tow['pay_status'] = array('IN','2,3');
        $where_tow['order_status'] = array('neq',2);
        //$where_tow['shipping_status'] = array('IN','0,3');	//未备货中
        $where_tow['wid'] = $wid;
        $where_tow['shipping_id'] = 3;
        $where_tow['sorting_id'] = 0;
        $where_tow['outgo']=0;	    //商品未出仓


        if($page==999){
            $list=M('order_info')->field('sorting_id,wp_userid,wid,wdr_id,postscript,best_time_start,best_time,wp_userid,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')
                ->where($where)->order('order_id desc')->select();
        }else{
            $count_unpicking=M('order_info')->where($where_tow)->count();
            //$listaddresstt =M('order_info')->getlastsql();
            $count=M('order_info')->where($where)->count();
            if($count==0){
                returnApiSuccess(array('list'=>array(),'is_last'=>1,'count_prepare'=>0,'count_unpicking'=>$count_unpicking),'无数据');
            }
            $pagearr=show_page($count, $page);
            if($page>=$pagearr['pagecount']){
                $is_last=1;
            }else{
                $is_last=0;
            }

            $list=M('order_info')->field('outgo,sorting_id,wp_userid,wid,wdr_id,postscript,best_time_start,best_time,wp_userid,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')
                ->where($where)->limit($pagearr['firstpage'].','.$pagearr['pagesize'])->order('order_id desc')->select();
        }




        if($list){
            $push_array = array();
            foreach ($list as $k=>$v){
                unset($one_order);

                $one_order = $this->get_order_info($v);
                $one_order['order_state'] = 1;  //配货中
                $re_goods_list = $this->re_goods_list($v['order_id'],$wid);
                if($re_goods_list){
                    $one_order['goods_list_back']=$re_goods_list;
                }
                $goods_list = $this->sh_goods_list($v['order_id'],$wid);
                if($goods_list){
                    $one_order['goods_list']=$goods_list;
                }
                array_push($push_array,$one_order);

            }
            returnApiSuccess(array('list'=>$push_array,'is_last'=>$is_last,'count_prepare'=>$count,'count_unpicking'=>$count_unpicking),'success');
        }else{
            returnApiError('数据为空');
        }
    }


    /**
     * 配货完成列表
     * rui poptser@foxmail.com 2016-10-10 10:09:19
     */
    // TODO 配货完成列表 deployed_list
    public function deployed_list(){
        $user_id=I('post.user_id','intval');

        if(!isset($user_id)){
            returnApiError('参数错误');
        }
        $this->check_user($user_id);
        $wid = $this->get_user_wid_identity($user_id);

        $page=I('post.page','intval');
        $year = I('post.year','intval');
        $month = I('post.month','intval');
        if($year>0 && $month>0){
            $days = date('t', strtotime($year."-".$month));
            $begintime = strtotime($year."-".$month."-1");
            $endtime = strtotime($year."-".$month."-".$days." 23:59:59");
            $where['sorting_time'] = array(array('EGT',$begintime),array('ELT',$endtime)) ; //
        }


        $where['sorting_id']=$user_id;
        $where['pay_status']=array("EGT",2);
        $where['order_status']=array("NEQ",2);
        $where['shipping_status']=array("in","5,1,2");;    //已发货
        $count=M('order_info')->where($where)->count();
//         $sql = M('order_info')->getLastSql();
        $pagearr=show_page($count, $page);
        if($page>=$pagearr['pagecount']){
            $is_last=1;
        }else{
            $is_last=0;
        }
        $list=M('order_info')->field('outgo,sorting_id,wp_userid,wid,wdr_id,postscript,best_time_start,best_time,wp_userid,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')->where($where)->limit($pagearr['firstpage'].','.$pagearr['pagesize'])->order('sorting_time desc,order_id desc')->select();
        if($list){
            $push_array = array();
            foreach ($list as $k=>$v){
                unset($one_order);

                $one_order = $this->get_order_info($v);
                $one_order['order_state'] = 2;  //配货中

                $re_goods_list = $this->re_goods_list($v['order_id'],$wid);
                if($re_goods_list){
                    $one_order['goods_list_back']=$re_goods_list;
                }
                $goods_list = $this->sh_goods_list($v['order_id'],$wid);
                if($goods_list){
                    $one_order['goods_list']=$goods_list;
                }
                array_push($push_array,$one_order);
                unset($one_order);
            }
            returnApiSuccess(array('list'=>$push_array,'is_last'=>$is_last,'count'=>$count,'sql'=>M('order_info')->getlastsql()),'success');
        }else{
            returnApiError("已返回全部");
            $list = array();
            $is_last =1;
            $count = 0;
            returnApiSuccess(array('list'=>$list,'is_last'=>$is_last,'count'=>$count),'success');
        }
    }

    /**
     * 搜索订单号(可使用订单号/收货人姓名/收货人手机号进行搜索)
     * rui poptser@foxmail.com 2016-10-11 11:00:40
     */
    // TODO 搜索订单 search_order
    public function search_order(){
        $user_id = I('post.user_id','intval');
        $key_words = I('post.key');
        $page=I('post.page','intval');

        $this->check_user($user_id);
        $wid = $this->get_user_wid_identity($user_id);

        if(empty($key_words)){
            returnApiError("关键字为空");
        }

        $where = " shipping_id = 3 AND
          wid = ".$wid."
          AND (order_sn LIKE '%" . $key_words . "%' OR consignee LIKE '%" . $key_words . "%' OR mobile LIKE '%" . $key_words . "%')";
        $count=M('order_info')->where($where)->count();
        $pagearr=show_page($count, $page);
        if($page>=$pagearr['pagecount']){
            $is_last=1;
        }else{
            $is_last=0;
        }

        $list=M('order_info')->field('outgo,wid,wdr_id,postscript,best_time_start,best_time,sorting_id,wp_userid,order_id,order_sn as order_num,order_status as order_state,shipping_status,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')
            ->where($where)->limit($pagearr['firstpage'].','.$pagearr['pagesize'])->order('add_time desc,order_id desc')->select();

        if($list){
            $push_array = array();
            foreach ($list as $k=>$v){
                $one_order = $this->get_order_info($v);
                if($v['order_state']!=2 && $v['sorting_id']==0){
                    $one_order['order_state']=0; //待配货
                }elseif ($v['order_state']!=2 && $v['sorting_id']!=0&&$v['shipping_status']==3){
                    $one_order['order_state']=1;  //配货中
                }elseif($v['order_state']!=2 && $v['shipping_status']==5){
                    $one_order['order_state']=2;  //完成配货
                }elseif($v['order_state']!=2 && $v['shipping_status']==1){
                    $one_order['order_state']=4;  //发货中
                }elseif($v['order_state']!=2 && $v['shipping_status']==2){
                    $one_order['order_state']=5;  //已送达
                }else{
                    returnApiError('此订单为错误订单');
                }

                $re_goods_list = $this->re_goods_list($v['order_id'],$wid);
                if($re_goods_list){
                    $one_order['goods_list_back']=$re_goods_list;
                }
                $goods_list = $this->sh_goods_list($v['order_id'],$wid);
                if($goods_list){
                    $one_order['goods_list']=$goods_list;
                }
                array_push($push_array,$one_order);
                unset($one_order);
            }
            returnApiSuccess(array('list'=>$push_array,'is_last'=>$is_last),'success');
        }else{
            returnApiError('数据为空');
        }

    }

    /**
     * 开始配货
     * rui poptser@foxmail.com 2016-10-11 11:32:22
     */
    // TODO 开始配货 deploy
    public function deploy(){

        $order_id = I('post.order_id','intval');    //订单号
        $user_id = I('post.user_id','intval');

        $this->check_user($user_id);    //检查用户
        $wid = $this->get_user_wid_identity($user_id);

        $result = $this->deploy_order_action($user_id,$order_id,$wid);
        if($result){
            returnApiSuccess(null,"已开始配货");
        }else{
            returnApiError("配货失败:\n联系客服查找配货失败原因");
        }
    }

    /**
     * 配货完成
     * rui poptser@foxmail.com 2016-10-11 14:28:17
     */
    // TODO 配货完成 deployed
    public function deployed(){
        $order_id = I('post.order_id','intval');    //订单号
        $user_id = I('post.user_id','intval');
        $this->check_user($user_id);    //检查用户
        $wid = $this->get_user_wid_identity($user_id);

        $where = "order_id = ".$order_id." AND wid = ".$wid;
        $where = $where." AND sorting_id = ".$user_id." AND shipping_status = 3 AND order_status!=2 AND pay_status >= 2";

        $data['sorting_id'] = $user_id;
        $data['shipping_status'] = 5;   //修改为完成配货
        $data['sorting_time'] = gmtime();
        $result = M("order_info")->where($where)->save($data);    //修改订单信息表中的
        if($result){
            //修改成功，写入日志
            $order_info = M("order_info")->where("order_id = ".$order_id)->find();
            $a=array(
                'order_id'=>$order_id,
                'user_id'=>$user_id,
                'order_status'=>$order_info['order_status'],
                'shipping_status'=>5,
                'pay_status'=>$order_info['pay_status'],
                'action_note'=>'配货完成'
            );

            A("Distribution")->record_diliveryman_log($a);//记录配送员操作日志
            returnApiSuccess(null,"已完成配货");
        }else{
            returnApiError("订单还未开始配货");
        }
    }


    /**
     * 获取订单商品详情
     * rui poptser@foxmail.com 2016-10-11 15:25:39
     */
    // TODO 获取订单商品详情 get_goods_handle_list
    public function get_goods_handle_list(){
        $order_id = I('post.order_id','intval');    //订单号
        $user_id = I('post.user_id','intval');

        $this->check_user($user_id);    //检查用户
        $wid = $this->get_user_wid_identity($user_id);


        if(!is_numeric($order_id)){
            returnApiError("订单ID错误");
        }


        $my_w_order = M("order_info")->where("order_id =".$order_id." AND wid = ".$wid)->getField('order_id');

        if($my_w_order){
            $rui_goods_list = array();
            $goods_list = $this->get_goods_list_real($my_w_order); //不包含赠品

            //dump($goods_list);

            foreach ($goods_list as $key=>$value){
                $goods_lists['count'] = $value['real_num'];
                $goods_lists['name'] = $value['goods_name'];
                $goods_lists['price'] = $value['goods_price'];
                $goods_lists['id'] = $value['rec_id'];
                $goods_lists['rec_id'] = $value['rec_id'];
                $goods_lists['act_id'] = $value['act_id'];
                $goods_lists['selected'] = $value['selected'];
                $goods_lists['order_id'] = $order_id;
                $goods_lists['goods_number'] = $value['goods_sn'];
                $goods_lists['giving'] = $value['giving'];
                $goods_lists['store_count'] = M("goods_storage")->where("goods_id =".$value['goods_id']." AND wid = ".$wid)->getField('practical_num');

                array_push($rui_goods_list,$goods_lists);
            }
            $data['goods_list']=$rui_goods_list;
            $data['note']=$my_w_order['postscript'];;


//            $goods=M("order_goods")->field('selected,goods_id as id,goods_name as name,goods_price as price,goods_number as `count`')->where(array('order_id'=>$my_w_order))->select();
//
//            $data['goods_list']=$goods;
            returnApiSuccess($data,'已返回商品列表');
        }else{
            returnApiError("不存在此订单/非本仓库");
        }
    }


    /**
     * 新建配货群组并将订单修改为配货中
     * rui poptser@foxmail.com 2016-10-11 15:25:39
     */
    // TODO 新建配货群组 group_create
    public function group_create(){
        $user_id = I('post.user_id','intval');
        $order_id_list = I('post.order_id_list');
        $name = I('post.name');
        $this->check_user($user_id);    //检查用户
        $wid = $this->get_user_wid_identity($user_id);

        $order_array = explode(",",$order_id_list);
        $order_array = array_filter($order_array);
        foreach ($order_array as $value){
            if(!is_numeric($value)&&!empty($value)){
                returnApiError("订单ID组错误");
                exit();
            }else{
                $r = M("order_info")->where("shipping_id =3 AND wid = ".$wid." AND order_id = ".$value." AND shipping_status in(0,3) AND sorting_id=0 AND order_status = 1 AND pay_status IN (2,3)")->count();
                if(!$r){
                    returnApiError("订单ID组中部分订单状态不正常");
                    exit();
                }
            }
        }

        $data['order_id'] = implode(",",$order_array);
        $data['group_name'] = $name;
        $data['user_id'] = $user_id;
        $data['wid'] = $wid;
        $data['addtime'] = time();
        $data['state'] = 0;

        $rs = M("sorting_order_group")->add($data);
        if($rs){
            $order_data['sorting_id']=$user_id;
            $order_data['shipping_status']=3;
            $where['order_id'] = array("in",$data['order_id']);
            $where['sorting_id'] = 0;
            $where['shipping_status'] = array("in","0,3");
            $new_order_list = M("order_info")->where($where)->getField("order_id",true);
            M("order_info")->where($where)->save($order_data);
            foreach ($new_order_list as $value){
                //写入日志
                $order_info = M("order_info")->where("order_id = ".$value)->find();
                $a=array(
                    'order_id'=>$value,
                    'user_id'=>$user_id,
                    'order_status'=>$order_info['order_status'],
                    'shipping_status'=>3,
                    'pay_status'=>$order_info['pay_status'],
                    'action_note'=>'备货中(群组操作)'
                );

                A("Distribution")->record_diliveryman_log($a);//记录配送员操作日志
            }

            returnApiSuccess(null,"新建群组成功");
        }
    }


    /**
     * 获取配货分组
     * rui poptser@foxmail.com 2016-10-11 17:32:48
     */
    // TODO 获取配货分组 group_list
    public function group_list(){
        $user_id=I('post.user_id','intval');

        if(!isset($user_id)){
            returnApiError('参数错误');
        }
        $this->check_user($user_id);
        $wid = $this->get_user_wid_identity($user_id);

        $page=I('post.page','intval');



        $where['state']=0;
        $where['user_id']=$user_id;
        $where['wid']=$wid;


        $count=M('sorting_order_group')->where($where)->count();
//         $sql = M('order_info')->getLastSql();
        $pagearr=show_page($count, $page);
        if($page>=$pagearr['pagecount']){
            $is_last=1;
        }else{
            $is_last=0;
        }
        $list=M('sorting_order_group')->field('id,group_name,order_id,state,addtime')->where($where)->limit($pagearr['firstpage'].','.$pagearr['pagesize'])->order('state asc,id desc')->select();
        if($list){
            foreach ($list as $k=>$v){

                $list[$k]['num_all'] = count(array_filter(array_unique(explode(",",$v['order_id']))));  //全部订单数
                $list[$k]['name'] = $v['group_name'];  //分组名称
                $list[$k]['time'] = date('Y-m-d H:i:s',$v['addtime']);  //时间

                $list[$k]['num_deploy'] = M("order_info")->where('shipping_status = 3 AND sorting_id !=0 AND order_id IN ('.$v['order_id'].')')->count();  //配货中
                $list[$k]['num_distribute'] = M("order_info")->where('shipping_status = 5 AND order_id IN ('.$v['order_id'].')')->count();  //配货完成

                $list[$k]['num_end'] = M("order_info")->where('shipping_status = 1 AND order_id IN ('.$v['order_id'].')')->count();  //已完成
                $list[$k]['end_state'] = $v['state'];  //时间





                $list[$k]['num_deploy']= M("order_info")->where("shipping_status = 3 AND order_id IN (".implode(',',array_filter(array_unique(explode(",",$v['order_id'])))).")")->count();//已配货数
            }
            returnApiSuccess(array('list'=>$list,'is_last'=>$is_last,'count'=>$count),'success');
        }else{
            $list = array();
            $is_last =1;
            $count = 0;
            returnApiSuccess(array('list'=>$list,'is_last'=>$is_last,'count'=>$count),'success');
        }
    }

    /**
     * 获取分组里面的订单列表
     * rui poptser@foxmail.com 2016-10-11 17:55:39
     */
    // TODO 获取分组订单列表 group_sub_list
    public function group_sub_list(){
        $user_id=I('post.user_id','');
        if(empty($user_id)){
            returnApiError('参数错误');
        }
        $this->check_user($user_id);
        $wid = $this->get_user_wid_identity($user_id);
        $page=I('post.page','intval');
        $group_id=I('post.group_id','');
        if(empty($group_id)){
            returnApiError('参数错误');
        }
        $where['sorting_id']=$user_id;
        $where['pay_status']=array('gt',1);
        $where['order_status']=array('neq',2);
        $where['wid']=$wid;

        $group_order = M("sorting_order_group")->where("wid = ".$wid." AND id = ".$group_id." AND user_id = ".$user_id)->getField("order_id");


        //$group_order = array_filter(array_unique(explode(",",$group_order)));

        $where['order_id'] = array('in',$group_order);
        $count=M('order_info')->where($where)->count();
        //dump(M('order_info')->getlastsql());
        if($count==0){
            returnApiSuccess(array('list'=>array(),'is_last'=>1,'count_prepare'=>0),'无数据');
        }
        $pagearr=show_page($count, $page);
        if($page>=$pagearr['pagecount']){
            $is_last=1;
        }else{
            $is_last=0;
        }

        $list=M('order_info')->field('outgo,wid,wdr_id,postscript,best_time_start,best_time,shipping_status,sorting_id,wp_userid,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')
            ->where($where)->limit($pagearr['firstpage'].','.$pagearr['pagesize'])->order('add_time desc,order_id desc')->select();

        if($list){
            $push_array = array();
            foreach ($list as $k=>$v){
                $one_order = $this->get_order_info($v);
                if($v['order_state']!=2 && $v['shipping_status']==0||$v['sorting_id']==0){
                    $one_order['order_state']=0; //待配货
                }elseif ($v['order_state']!=2 && $v['shipping_status']==3&&$v['sorting_id']!=0){
                    $one_order['order_state']=1;  //配货中
                }elseif($v['order_state']!=2 && $v['shipping_status']==5){
                    $one_order['order_state']=2;  //完成配货
                }elseif($v['order_state']!=2 && $v['shipping_status']==1){
                    $one_order['order_state']=4;  //发货中
                }elseif($v['order_state']!=2 && $v['shipping_status']==2){
                    $one_order['order_state']=5;  //已送达
                }else{
                    returnApiError('此订单为错误订单');
                }

                $re_goods_list = $this->re_goods_list($v['order_id'],$wid);
                if($re_goods_list){
                    $one_order['goods_list_back']=$re_goods_list;
                }
                $goods_list = $this->sh_goods_list($v['order_id'],$wid);
                if($goods_list){
                    $one_order['goods_list']=$goods_list;
                }
                array_push($push_array,$one_order);
                unset($one_order);
            }
            returnApiSuccess(array('list'=>$push_array,'is_last'=>$is_last),'success');
        }else{
            returnApiError('数据为空');
        }
    }


    /**
     * 群组配送完成
     * rui poptser@foxmail.com 2016-10-12 09:29:48
     */
    // TODO 群组配送完成 group_deployed
    public function group_deployed(){
        $user_id=I('post.user_id','intval');
        if(!isset($user_id)){
            returnApiError('参数错误');
        }
        $this->check_user($user_id);
        $wid = $this->get_user_wid_identity($user_id);
        $group_id=I('post.group_id','');
        if(empty($group_id)){
            returnApiError('参数错误');
        }
        $group_order = M("sorting_order_group")->where("wid = ".$wid." AND id = ".$group_id." AND user_id = ".$user_id)->getField("order_id");
        $group_order = array_filter(array_unique(explode(",",$group_order)));
        $where['order_id'] = array('in',$group_order);
        $where['sorting_id']=$user_id;
        $where['pay_status']=array('gt',1);
        $where['order_status']=array('neq',2);
        $where['wid']=$wid;
        $where['shipping_status']=3;
        $order_data['shipping_status']=5;
        $new_order_list = M("order_info")->where($where)->getField("order_id",true);
        M("order_info")->where($where)->save($order_data);

        foreach ($new_order_list as $value){
            //写入日志
            $a=array(
                'order_id'=>$value,
                'user_id'=>$user_id,
                'order_status'=>1,
                'shipping_status'=>5,
                'pay_status'=>2,
                'action_note'=>'备货完成(群组操作)'
            );
            A("Distribution")->record_diliveryman_log($a);//记录配送员操作日志
        }
        M("sorting_order_group")->where("id =".$group_id)->setField("state",1);

        returnApiSuccess(null,"群组配货完成");

    }


    /**
     * 扫描二维码获取订单
     * rui poptser@foxmail.com 2016-10-10 17:11:20
     */
    // TODO 扫描二维码获取订单 scanner
    public function scanner(){
        $wp_userid=I('post.user_id','intval');
        $order_id=I('post.barcode');    //扫描得到的订单ID
        $order_number=I('post.order_number');   //手动输入的订单号后8位

        if(empty($order_id)){
            if(!isset($wp_userid) || !isset($order_number)){
                if(!is_numeric($order_number)){
                    returnApiError('参数错误');
                }
            }
        }else{
            if(!isset($wp_userid) || !isset($order_id)){
                returnApiError('参数错误');
            }
        }


        $this->check_user($wp_userid);

        $wid = $this->get_user_wid_identity($wp_userid);
        //$where['wp_userid']=$wp_userid;

        if(empty($order_id)){
            $where['order_sn']=array("like","%".$order_number);
        }else{
            $where['order_id']=$order_id;
        }


        $where['pay_status']=array('gt',1);
        $where['order_status']=array('neq',2);
        $where['wid']=$wid;
        $where['shipping_id']=3;
        $where['outgo']=0;
        $where['_string'] = "(is_presell = 0 OR (is_presell = 1 AND buckle_inventory = 1))";
        $order=M('order_info')->field('outgo,wid,wdr_id,postscript,best_time_start,best_time,sorting_id,wp_userid,order_id,order_sn as order_num,order_status as order_state,shipping_status,add_time as order_time,consignee as name,mobile as phone,sign_building,country,province,city,district,address,sorting_id')->where($where)->find();

        if($order){
            try {
                if($order['sorting_id']==0 || $order['sorting_id']==$wp_userid){


                    $data = $this->get_order_info($order);

                    //dump($data);


                    if ($order['sorting_id'] == 0) {
                        $data['order_state'] = 0; //待配货
                    } elseif ($order['sorting_id'] != 0&&($order['shipping_status']==3 ||$order['shipping_status']==0)) {
                        $data['order_state'] = 1;  //配货中
                    } elseif ($order['shipping_status'] == 5) {
                        $data['order_state'] = 2;  //完成配货
                    } elseif ($order['shipping_status'] == 1) {
                        $data['order_state'] = 4;  //发货中
                    } elseif ($order['shipping_status'] == 2) {
                        $data['order_state'] = 5;  //已送达
                    }

                    $goods_list = $this->sh_goods_list($order['order_id'],$wid);
                    if($goods_list){
                        $data['goods_list']=$goods_list;
                    }
                    $re_goods_list = $this->re_goods_list($order['order_id'],$wid);
                    if($re_goods_list){
                        $data['goods_list_back']=$re_goods_list;
                    }

                    returnApiSuccess(array('distribute'=>$data));
                }else{
                    returnApiError('此单已被其它配货员操作'.$order['sorting_id']);
                }
            }catch (Exception $e){
                returnApiErrorExample($e->getMessage());
            }
        }else{
            returnApiError('查无此条码/非本仓库订单/订单不可配货/预售单');
        }
    }


    /**
     * 获取订单筛选条件
     * rui poptser@foxmail.com 2016-10-21 15:04:25
     */
    // TODO 获取订单筛选条件 get_order_condition
    public function get_order_condition(){
        $wp_userid=I('post.user_id','intval');
        if(!isset($wp_userid)){
            returnApiError('参数错误');
        }
        $this->check_user($wp_userid);
        $wid = $this->get_user_wid_identity($wp_userid);

        $year     =I('post.year','intval');     //年份
        $month    =I('post.month','intval');    //月份
        $day      =I('post.day','intval');      //日期
        $default_order  =I('post.default_order','intval');  //是否为活动单
        $is_ps=I('post.is_ps');
        if(empty($is_ps)){
            //配货
            $where_tow['shipping_status']= array('in','0,3');	//未备货中
            $where_tow['sorting_id']=0;	//未备货中
            $where_tow['wid']=$wid;
            $where_tow['outgo']=0;	    //商品未出仓
        }else{
            //配送
            $where_tow['shipping_status']= 5;	//已配货完成
            $where_tow['wp_userid']=0;	//无配送员接单
            $where_tow['outgo']=1;	    //商品已经出仓
        }
        $where_tow['pay_status']=array('in','2,3');
        $where_tow['order_status']= array('neq',2);

        $where_tow['shipping_id']=3;        //送货上门订单

        //配送时间
        if($default_order==0){
            //活动单
            $where_list = "(is_presell = 0 OR (is_presell = 1 AND buckle_inventory = 1)) AND goods_amount = 1 AND ";
        }else{
            //常规单
            $where_list = "(is_presell = 0 OR (is_presell = 1 AND buckle_inventory = 1)) AND goods_amount != 1 AND ";
        }

        $where_1 = $where_list."best_time_start='".strtotime($year."-".$month."-".$day." 10:00:00")."'  AND best_time='".strtotime($year."-".$month."-".$day." 12:00:00")."'";
        $where_2 = $where_list."best_time_start='".strtotime($year."-".$month."-".$day." 12:00:00")."'  AND best_time='".strtotime($year."-".$month."-".$day." 14:00:00")."'";
        $where_3 = $where_list."best_time_start='".strtotime($year."-".$month."-".$day." 14:00:00")."'  AND best_time='".strtotime($year."-".$month."-".$day." 16:00:00")."'";
        $where_4 = $where_list."best_time_start='".strtotime($year."-".$month."-".$day." 16:00:00")."'  AND best_time='".strtotime($year."-".$month."-".$day." 18:00:00")."'";
        $where_5 = $where_list."best_time_start='".strtotime($year."-".$month."-".$day." 18:30:00")."'  AND best_time='".strtotime($year."-".$month."-".$day." 20:30:00")."'";
        $where_6 = $where_list."best_time_start='".strtotime($year."-".$month."-".$day." 10:00:00")."'  AND best_time='".strtotime($year."-".$month."-".$day." 20:30:00")."'";
        $where_7 = $where_list."best_time_start='".strtotime($year."-".$month."-".$day." 20:30:00")."'  AND best_time='".strtotime($year."-".$month."-".$day." 22:00:00")."'";
        $where_8 = $where_list."best_time_start='".strtotime($year."-".$month."-".$day." 10:00:00")."'  AND best_time='".strtotime($year."-".$month."-".$day." 22:00:00")."'";
        $where_9 = $where_list."TO_DAYS('".$year."-".$month."-".$day." 10:00:00"."') >  TO_DAYS(from_unixtime(best_time))";


        $str_num = M('order_info')->where($where_1)->where($where_tow)->count();
        if($str_num>0){$str_1 = " ( ".$str_num." )";}else{$str_1 = "";}
        $str_num = M('order_info')->where($where_2)->where($where_tow)->count();
        if($str_num>0){$str_2 = " ( ".$str_num." )";}else{$str_2 = "";}
        $str_num = M('order_info')->where($where_3)->where($where_tow)->count();
        if($str_num>0){$str_3 = " ( ".$str_num." )";}else{$str_3 = "";}
        $str_num = M('order_info')->where($where_4)->where($where_tow)->count();
        if($str_num>0){$str_4 = " ( ".$str_num." )";}else{$str_4 = "";}
        $str_num = M('order_info')->where($where_5)->where($where_tow)->count();
        if($str_num>0){$str_5 = " ( ".$str_num." )";}else{$str_5 = "";}
        $str_num = M('order_info')->where($where_6)->where($where_tow)->count();
        if($str_num>0){$str_6 = " ( ".$str_num." )";}else{$str_6 = "";}
        $str_num = M('order_info')->where($where_7)->where($where_tow)->count();
        if($str_num>0){$str_7 = " ( ".$str_num." )";}else{$str_7 = "";}
        $str_num = M('order_info')->where($where_8)->where($where_tow)->count();
        if($str_num>0){$str_8 = " ( ".$str_num." )";}else{$str_8 = "";}
        $str_num = M('order_info')->where($where_9)->where($where_tow)->count();
        if($str_num>0){$str_9 = " ( ".$str_num." )";}else{$str_9 = "";}

        $data['list_time']=array(
            array(
                "id" =>1,
                "value" =>"10:00 - 12:00 ".$str_1
            ),
            array(
                "id" =>2,
                "value" =>"12:00 - 14:00 ".$str_2
            ),
            array(
                "id" =>3,
                "value" =>"14:00 - 16:00 ".$str_3
            ),
            array(
                "id" =>4,
                "value" =>"16:00 - 18:00 ".$str_4
            ),
            array(
                "id" =>5,
                "value" =>"18:30 - 20:30 ".$str_5
            ),
            array(
                "id" =>7,
                "value" =>"20:30 - 22:00 ".$str_7
            ),
            array(
                "id" =>6,
                "value" =>"10:00 - 20:30 ".$str_6
            ),
            array(
                "id" =>8,
                "value" =>"10:00 - 22:00 ".$str_8
            ),
            array(
                "id" =>9,
                "value" =>"过往订单 ".$str_9
            )
        );

        //全部单
        $data['count_prepare'] = M('order_info')->where($where_tow)->where("TO_DAYS(from_unixtime(best_time)) <= TO_DAYS('".$year."-".$month."-".$day." 10:00:00')")->count();
        $data['count_prepare_ys'] = M('order_info')->where($where_tow)->where("is_presell = 1 AND buckle_inventory = 0 AND TO_DAYS(from_unixtime(best_time)) <= TO_DAYS('".$year."-".$month."-".$day." 10:00:00')")->count();

        //活动订单数量
        $data['count_order_activity'] = M('order_info')->where($where_tow)->where("goods_amount = 1 AND TO_DAYS(from_unixtime(best_time)) <= TO_DAYS('".$year."-".$month."-".$day." 10:00:00')")->count();
        $data['count_order_activity_ys'] = M('order_info')->where($where_tow)->where("is_presell = 1 AND buckle_inventory = 0 AND goods_amount = 1 AND TO_DAYS(from_unixtime(best_time)) <= TO_DAYS('".$year."-".$month."-".$day." 10:00:00') ")->count();


        //常规订单数量
        $data['count_order_default'] =M('order_info')->where($where_tow)->where("goods_amount <> 1 AND TO_DAYS(from_unixtime(best_time)) <= TO_DAYS('".$year."-".$month."-".$day." 10:00:00')")->count();;
        $data['sql'] = M('order_info')->getlastsql();
        $data['count_order_default_ys'] =M('order_info')->where($where_tow)->where("is_presell = 1 AND buckle_inventory = 0 AND goods_amount <> 1  AND TO_DAYS(from_unixtime(best_time)) <= TO_DAYS('".$year."-".$month."-".$day." 10:00:00')")->count();

        $data['count_prepare'] = $data['count_prepare']." ( 预:".$data['count_prepare_ys']." )";
        $data['count_order_activity'] = $data['count_order_activity']." ( 预:".$data['count_order_activity_ys']." )";
        $data['count_order_default'] = $data['count_order_default']." ( 预:".$data['count_order_default_ys']." )";
        returnApiSuccess($data,"已返回数据");
    }


    /**
     * 获取送货区域订单数
     * TODO 根据时间，送货区域获取订单(仅订单数) get_order_condition_area
     */
    public function get_order_condition_area(){
        $wp_userid=I('post.user_id','intval');  //用户ID
        $year     =I('post.year','intval');     //年份
        $month    =I('post.month','intval');    //月份
        $day      =I('post.day','intval');      //日期
        $time_id  =I('post.time_id','intval');  //配送时间段ID
        $default_order  =I('post.default_order','intval');  //是否为活动单
        if(empty($wp_userid)||empty($year)||empty($month)||empty($day)||empty($time_id)){
            returnApiError('参数错误');
        }
        $this->check_user($wp_userid);

        $wid = $this->get_user_wid_identity($wp_userid);
        //dump($wid);
        $other =  false;

        $where_tow['pay_status']=array('in','2,3');
        $where_tow['order_status']= array('neq',2);


        $where_tow['shipping_id']=3;        //送货上门订单

        switch ($time_id){
            case 1:
                $start_time = "10:00:00";
                $end_time = "12:00:00";
                break;
            case 2:
                $start_time = "12:00:00";
                $end_time = "14:00:00";
                break;
            case 3:
                $start_time = "14:00:00";
                $end_time = "16:00:00";
                break;
            case 4:
                $start_time = "16:00:00";
                $end_time = "18:00:00";
                break;
            case 5:
                $start_time = "18:30:00";
                $end_time = "20:30:00";
                break;
            case 6:
                $start_time = "10:00:00";
                $end_time = "20:30:00";
                break;
            case 7:
                $start_time = "20:30:00";
                $end_time = "22:00:00";
                break;
            case 8:
                $start_time = "10:00:00";
                $end_time = "22:00:00";
                break;
            case 9:
                //非当天单
                $other =  true;
                break;
            default:
                returnApiError("时间点错误");
                break;
        }
        try{
            $best_time_str = $year."-".$month."-".$day." 12:00:00";
            if($other){
                if($default_order==0){
                    //活动单
                    $where['_string'] = "(`is_presell` = 0 OR (`is_presell` = 1 AND `buckle_inventory` = 1)) AND TO_DAYS('".$best_time_str."') > TO_DAYS(from_unixtime(`best_time`)) AND `goods_amount` = 1";
                }else{
                    //常规单
                    $where['_string'] = "(`is_presell` = 0 OR (`is_presell` = 1 AND `buckle_inventory` = 1)) AND TO_DAYS('".$best_time_str."') > TO_DAYS(from_unixtime(`best_time`)) AND `goods_amount` != 1";
                }
            }else{
                $where['_string'] = "(`is_presell` = 0 OR (`is_presell` = 1 AND `buckle_inventory` = 1))";
                $where['best_time_start']=$best_time_start = strtotime($year."-".$month."-".$day." ".$start_time);
                $where['best_time']=$best_time = strtotime($year."-".$month."-".$day." ".$end_time);
                if($default_order==0){
                    //活动单
                    $where['goods_amount'] = 1;
                }else{
                    //常规单
                    $where['goods_amount'] = array('neq',1);
                }
            }

        }catch (Exception $s){
            returnApiError("时间点错误");
        }



        //配送区域
        $data['list_area'] = array();
        $is_ps=I('post.is_ps');
        if(empty($is_ps)){
            //配货端
            //按具体订单方式筛选订单
            $where_tow['wid']=$wid;
            $where_tow['shipping_status']= array('in','0,3');	//未备货中
            $where_tow['sorting_id']=0;	//未备货中
            $where_tow['outgo']=0;	    //商品未出仓


            if($default_order==0){
                //活动单
                $new_data = M('order_info')->where($where)->where($where_tow)->getField('wdr_id',true);
                $data['sql'] = M('order_info')->getlastsql();
            }else{
                //常规单
                $new_data = M('order_info')->where($where)->where($where_tow)->getField('wdr_id',true);
                $data['sql3'] = M('order_info')->getlastsql();
            }

            //$data['sql2'] = $default_order;
            foreach ($new_data as $key=>$value){
                //id  name  count
                $j=true;
                foreach ($data['list_area'] as $key2=>$value2){
                    if($value ==$value2['id']){
                        $j=false;
                    }
                }
                if($j){
                    $my_data['id'] = $value;
                    if($value==0){
                        $my_data['name'] ="未定义区域";
                    }else{
                        $my_data['name'] = M("warehouse_deliver_region")->where(array("id"=>$value))->getField("name");
                    }
                    $count_array = array_count_values($new_data);
                    $my_data['count'] = $count_array[$value];
                    array_push($data['list_area'],$my_data);
                }
            }

            $data['count_prepare'] = 0;
            $data['count_order_activity'] = 0;
            $data['count_order_default'] = 0;

        }else{
            //配送端
            //按具体订单方式筛选订单

            $where_tow['shipping_status']= 5;	//配货完成
            $where_tow['wp_userid']=0;	//配送员ID 为空
            $where_tow['outgo']=1;	    //商品已经出仓
            if($default_order==0){
                //活动单
                $new_data = M('order_info')->where($where)->where($where_tow)->getField('wdr_id',true);
                $data['sql'] = M('order_info')->getlastsql();
            }else{
                //常规单
                $new_data = M('order_info')->where($where)->where($where_tow)->getField('wdr_id',true);
                $data['sql3'] = M('order_info')->getlastsql();
            }

            //$data['sql2'] = $default_order;
            foreach ($new_data as $key=>$value){
                //id  name  count
                $j=true;
                foreach ($data['list_area'] as $key2=>$value2){
                    if($value ==$value2['id']){
                        $j=false;
                    }
                }
                if($j){
                    $my_data['id'] = $value;
                    if($value==0){
                        $my_data['name'] ="未定义区域";
                    }else{
                        $my_data['name'] = M("warehouse_deliver_region")->where(array("id"=>$value))->getField("name");
                    }
                    $count_array = array_count_values($new_data);
                    $my_data['count'] = $count_array[$value];
                    array_push($data['list_area'],$my_data);
                }
            }

            $data['count_prepare'] = 0;
            $data['count_order_activity'] = 0;
            $data['count_order_default'] = 0;
        }


        returnApiSuccess($data,"已返回数据");
    }


    /**
     * 随机获取一条当前仓库的订单
     * rui poptser@foxmail.com 2016-10-20 13:58:38
     */
    // TODO 随机获取一条当前仓库的订单 get_order
    public function get_order(){
        $wp_userid=I('post.user_id','intval');  //用户ID
        $year     =I('post.year','intval');     //年份
        $month    =I('post.month','intval');    //月份
        $day      =I('post.day','intval');      //日期
        $time_id  =I('post.time_id','intval');  //配送时间段ID
        $area_id  =I('post.area_id','intval');  //配送区域ID
        $default_order  =I('post.default_order','intval');  //是否为活动订单
        if(empty($wp_userid)||empty($year)||empty($month)||empty($day)||empty($time_id)){
            returnApiError('参数错误');
        }
        $this->check_user($wp_userid);
        $wid = $this->get_user_wid_identity($wp_userid);

        if(isset($area_id)){
            $where['wdr_id'] = $area_id;
        }


        $where['_string'] = "(is_presell = 0 OR (is_presell = 1 AND buckle_inventory = 1))";    //现售条件
        $other =  false;
        switch ($time_id){
            case 1:
                $start_time = "10:00:00";
                $end_time = "12:00:00";
                break;
            case 2:
                $start_time = "12:00:00";
                $end_time = "14:00:00";
                break;
            case 3:
                $start_time = "14:00:00";
                $end_time = "16:00:00";
                break;
            case 4:
                $start_time = "16:00:00";
                $end_time = "18:00:00";
                break;
            case 5:
                $start_time = "18:30:00";
                $end_time = "20:30:00";
                break;
            case 6:
                $start_time = "10:00:00";
                $end_time = "20:30:00";
                break;
            case 7:
                $start_time = "20:30:00";
                $end_time = "22:00:00";
                break;
            case 8:
                $start_time = "10:00:00";
                $end_time = "22:00:00";
                break;
            case 9:
                $other =  true;
                break;
            default:
                returnApiError("时间点错误");
                break;
        }
        try{
            $best_time_str = $year."-".$month."-".$day." 12:00:00";
            if($other){
                $where['_string'] = "(is_presell = 0 OR (is_presell = 1 AND buckle_inventory = 1)) AND TO_DAYS('".$best_time_str."') >  TO_DAYS(from_unixtime(best_time))";
            }else{
                $where['best_time_start']=$best_time_start = strtotime($year."-".$month."-".$day." ".$start_time);
                $where['best_time']=$best_time = strtotime($year."-".$month."-".$day." ".$end_time);
            }
        }catch (Exception $s){
            returnApiError("时间点错误");
        }

        //查询是否有未完成的 随机获取单

        $is_ps=I('post.is_ps');

        if(empty($is_ps)) {
            //exit("ddd");
            //todo 随机获取订单 配货
            $where['sorting_id'] = 0;
            $where['shipping_status'] = array("in","0,3");
            $where['order_status'] = array("neq",2);
            $where['pay_status'] = array("in","2,3");
            $where['shipping_id']=3;
            $where['wid'] = $wid;
            $where['outgo']=0;	    //商品未出仓

            $where_random['sorting_id'] = $wp_userid;
            $where_random['is_random'] = 1;
            $where_random['shipping_status'] = array("in","0,3");
            $where_random['order_status'] = array("neq",2);
            $where_random['pay_status'] = array("in","2,3");
            $where_random['shipping_id']=3;

            $random_num = M("order_info")->field('postscript,best_time_start,best_time,wp_userid,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')
                ->where($where_random)->count();
            if($random_num>49){
                returnApiError("ヾ(≧O≦)〃嗷~\n已达50个订单\n请先完成配货");
            }

            if($default_order==1){
                $where['goods_amount'] = array("neq",1);
                $result = M("order_info")->field('sorting_id,wdr_id,wid,postscript,best_time_start,best_time,wp_userid,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')
                    ->order('rand()')->where($where)->find();
            }else{
                $where['goods_amount'] = 1;
                $result = M("order_info")->field('sorting_id,wdr_id,wid,postscript,best_time_start,best_time,wp_userid,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')
                    ->order('rand()')->where($where)->find();
            }
            //dump(M("order_info")->getlastsql());

            if($result){

                //$data['deploySSSS'] = M("order_info")->getlastsql();
                $this->deploy_order_action($wp_userid,$result['order_id'],$wid,true);

                $result = $this->get_order_info($result);

                $old_data = M("order_info")->where('order_id = '.$result['order_id'])->find();
                if ($old_data['sorting_id'] == 0) {
                    $data['order_state'] = 0; //待配货
                } elseif ($old_data['sorting_id'] != 0&&($old_data['shipping_status']==3 ||$old_data['shipping_status']==0)) {
                    $data['order_state'] = 1;  //配货中
                } elseif ($old_data['shipping_status'] == 5) {
                    $data['order_state'] = 2;  //完成配货
                } elseif ($old_data['shipping_status'] == 1) {
                    $data['order_state'] = 4;  //发货中
                } elseif ($old_data['shipping_status'] == 2) {
                    $data['order_state'] = 5;  //已送达
                }
                $goods_list = $this->sh_goods_list($result['order_id'],$wid);
                if($goods_list){
                    $result['goods_list']=$goods_list;
                }
                $re_goods_list = $this->re_goods_list($result['order_id'],$wid);
                if($re_goods_list){
                    $result['goods_list_back']=$re_goods_list;
                }
                $default_order = M("activity_quota")->where("order_id=" . $result['order_id'])->count();
                if ($default_order > 0) {
                    $result['default_order'] = 0;
                } else {
                    $result['default_order'] = 1;
                }
                $data['deploy'] = $result;
                returnApiSuccess($data,'已返回配货单');
            }else{
                returnApiError('数据为空');
            }
        }else {
            //TODO 随机获取订单  配送
            //dump('配送');
            $weight = I("post.weight");     //获取商品重量（单位KG）

            $where['wp_userid'] = 0;
            $where['shipping_status'] = 5;
            $where['order_status'] = array("neq", 2);
            $where['pay_status'] = array("in", "2,3");
            $where['shipping_id'] = 3;
            $where['outgo']=1;	    //商品已经出仓


            $where_random['wp_userid'] = $wp_userid;
            $where_random['is_random_ps'] = 1;
            $where_random['shipping_status'] = 5;
            $where_random['order_status'] = array("neq", 2);
            $where_random['pay_status'] = array("in", "2,3");
            $where_random['shipping_id'] = 3;
            $where_random['outgo']=1;	    //商品已经出仓

            $random_num = M("order_info")->field('postscript,best_time_start,best_time,wp_userid,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')
                ->where($where_random)->count();
            if ($random_num > 49) {
                returnApiError("ヾ(≧O≦)〃嗷~\n已达50个订单\n请先完成配送");
            }

            if($default_order==1){
                $where['goods_amount'] = array("neq",1);
                $result = M("order_info")->field('sorting_id,wdr_id,wid,postscript,best_time_start,best_time,wp_userid,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')
                    ->order('rand()')->where($where)->find();
            }else{
                $where['goods_amount'] = 1;
                $result = M("order_info")->field('sorting_id,wdr_id,wid,postscript,best_time_start,best_time,wp_userid,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')
                    ->order('rand()')->where($where)->find();
            }
            //dump($result);
            if ($result) {
                //$data['deploySSSS'] = M("order_info")->getlastsql();
                //returnApiError($result['order_num']);
                $this->distribute_order_action($wp_userid, $result['order_id'], $wid, true);

                $result = $this->get_order_info($result);

                if ($result['sorting_id'] == 0) {
                    $data['order_state'] = 0; //待配货
                } elseif ($result['sorting_id'] != 0&&($result['shipping_status']==3 ||$result['shipping_status']==0)) {
                    $data['order_state'] = 1;  //配货中
                } elseif ($result['shipping_status'] == 5) {
                    $data['order_state'] = 2;  //完成配货
                } elseif ($result['shipping_status'] == 1) {
                    $data['order_state'] = 4;  //发货中
                } elseif ($result['shipping_status'] == 2) {
                    $data['order_state'] = 5;  //已送达
                }
                $goods_list = $this->sh_goods_list($result['order_id'], $wid);
                if ($goods_list) {
                    $result['goods_list'] = $goods_list;
                }
                $re_goods_list = $this->re_goods_list($result['order_id'], $wid);
                if ($re_goods_list) {
                    $result['goods_list_back'] = $re_goods_list;
                }
                $default_order = M("activity_quota")->where("order_id=" . $result['order_id'])->count();
                if ($default_order > 0) {
                    $result['default_order'] = 0;
                } else {
                    $result['default_order'] = 1;
                }
                $data['deploy'] = $result;
                returnApiSuccess($data, '已返回配送单');
            } else {
                returnApiError('数据为空');
            }

        }

    }

    /**
     * 订单打印
     * rui poptser@foxmail.com 2016-10-21 14:43:29
     */
    // TODO 订单打印 order_print
    public function order_print(){
        $wp_userid=I('post.user_id','intval');  //用户ID
        $order_id     =I('post.order_id','intval');     //订单ID
        if(empty($wp_userid)||empty($order_id)){
            returnApiError('参数错误');
        }
        $this->check_user($wp_userid);

        $wid = $this->get_user_wid_identity($wp_userid);
        $distribute_info = A("Distribution")->get_admin_user_name($wp_userid);


        $Model=new Model();
        // 订单详情
        $total_fee = " (a.goods_amount - a.discount + a.tax + a.shipping_fee + a.insure_fee + a.pay_fee + a.pack_fee + a.card_fee) AS total_fee ";
        $sql = "SELECT a.*,b.name AS 'region_name'," . $total_fee . " FROM sdx_order_info AS a  LEFT JOIN sdx_warehouse_deliver_region AS b ON b.id=a.wdr_id WHERE a.order_id=" . $order_id;
        $order = $Model->query($sql);

        $order= $order[0];

        /* 格式化订单字段 */
        if (!empty($order)) {
            $order['formated_goods_amount'] = price_format($order['goods_amount'], false);
            $order['formated_discount'] = price_format($order['discount'], false);
            $order['formated_tax'] = price_format($order['tax'], false);
            $order['formated_shipping_fee'] = price_format($order['shipping_fee'], false);
            $order['formated_insure_fee'] = price_format($order['insure_fee'], false);
            $order['formated_pay_fee'] = price_format($order['pay_fee'], false);
            $order['formated_pack_fee'] = price_format($order['pack_fee'], false);
            $order['formated_card_fee'] = price_format($order['card_fee'], false);
            $order['formated_total_fee'] = price_format($order['total_fee'] - $order['refund_amount'], false);
            $order['formated_money_paid'] = price_format($order['money_paid'], false);
            $order['formated_bonus'] = price_format($order['bonus'], false);
            $order['formated_integral_money'] = price_format($order['integral_money'], false);
            $order['formated_surplus'] = price_format($order['surplus'], false);
            $order['formated_order_amount'] = price_format(abs($order['order_amount']), false);
            $order['formated_add_time'] = local_date(C('time_format'), $order['add_time']);
        }else{
            returnApiError("未查询到此单");
        }
        //配送地址处理
        $order['address'] = $order['address'] . $order['sign_building'] . $order['address_name'];

        //期望时间处理
        if (!empty($order['best_time'])) {
            if ($order['best_time_start'] > 0) {
                $best_time_start = date('Y-m-d H:i', $order['best_time_start']);
            } else {
                $best_time_start = date('Y-m-d H:i', $order['best_time'] - 7199);
            }
            $order['best_time'] = $best_time_start . "  -   " . date('H:i', $order['best_time'] + 1);
        }
        // 订单商品
        $sql = "SELECT og.rec_id, og.goods_id, og.goods_name, og.goods_sn, og.market_price, og.goods_number, " .
            "og.goods_price, og.goods_attr, og.is_real, og.parent_id, og.is_gift, " .
            "og.goods_price * og.goods_number AS subtotal, og.extension_code,og.is_presell,og.buckle_inventory, g.goods_thumb " .
            "FROM sdx_order_goods as og left join sdx_goods g on og.goods_id = g.goods_id" .
            " WHERE og.order_id = '$order_id'";
        $res = $Model->query($sql);
        foreach ($res as $row) {
            $goods_list[] = $row;
        }

        //退款
        $sql = "SELECT a.goods_id,a.goods_name,a.refund_number,a.refund_amount,b.goods_price,b.goods_sn
            FROM(SELECT goods_id,goods_name,SUM(refund_number) AS refund_number,SUM(refund_amount) AS refund_amount 
            FROM sdx_refund_detail WHERE order_id=$order_id GROUP BY goods_id,goods_name) AS a LEFT JOIN sdx_order_goods b ON b.order_id=$order_id AND b.goods_id=a.goods_id";
        $refund_data = M()->query($sql);
        $refund_goods = array();
        $refund_num = 0;
        $refund_price = 0;
        if ($refund_data) {
            foreach ($refund_data as $item) {
                $refund_goods[$item['goods_id']] = $item;
                $refund_num = $refund_num + $item['refund_number'];
                $refund_price = $refund_price + $item['refund_amount'];
            }
        }

        //计算优惠金额
        $market_fee = 0;
        foreach ($goods_list as $key => $item) {
            $market_fee += $item['market_price'] * $item['goods_number'];
            $val = 0;
            if ($refund_goods[$item['goods_id']]) {
                $val = $item['goods_number'] - ceil($refund_goods[$item['goods_id']]['refund_number']);
                if ($val > 0) {
                    $goods_list[$key]['goods_number'] = $val;
                } else {
                    unset($goods_list[$key]);
                }
            }
        }

        //查询商品退款信息
        $refund_str = "";
        $refund_num = 0;
        $refund_price = 0;
        //$refund_detail = M("refund_detail")->where('order_id ='.$order_id)->select();
        $refund_detail = M()->field('refund.goods_name,refund.refund_number,refund.refund_amount,goods.goods_price')->
        table('sdx_refund_detail as refund,sdx_order_goods as goods')->where('refund.goods_id = goods.goods_id AND refund.order_id = goods.order_id AND refund.order_id ='.$order_id)->select();
        if($refund_detail){
            $refund_str = "\n============退货信息============\n";
            foreach ($refund_detail as $value){
                $refund_str = $refund_str.$value['goods_name']."\n数量:".$value['refund_number']."  单价:".$value['goods_price']."  小计:".$value['refund_amount']."\n";
                $refund_num = $refund_num + $value['refund_number'];
                $refund_price = $refund_price + $value['refund_amount'];
            }
            $refund_str = $refund_str."合计：    ".$refund_num."    ".$refund_price;
        }

        $goods_str = "";

//        foreach ($goods_list as $key=>$value){
//            $goods_str = $goods_str.$value['goods_name']."\n货号:".$value['goods_sn']."\n数量:".$value['goods_number']." 单价:".$value['goods_price']." 小计:".$value['subtotal']."\n";
//        }

        $goods_list = $this->get_goods_list_real($order_id);
        foreach ($goods_list as $key => $value) {
            $goods_type = "";
            switch ($value['giving']){
                case 0:
                    //正常商品
                    break;
                case 1:
                    $goods_type = " [ 赠 ]";
                    break;
                case 2:
                    $goods_type = " [ 换 ]";
                    break;
                case 3:
                    $goods_type = " [ 抢 ]";
                    break;
                case 4:
                    $goods_type = " [ 促 ]";
                    break;
            }

            if($value['discount_price']>0){
                $this_goods_price = $value['discount_price'];
            }else{
                $this_goods_price = $value['goods_price'];
            }
            $goods_str = $goods_str.$value['goods_name'].$goods_type."\n货号:".$value['goods_sn']."\n价:".$value['goods_price']."x ".$value['real_num']." 折:".$value['goods_discount']." 计:".$value['real_num']*$this_goods_price."\n";
        }


        $pay_str = null;
        if($order['money_paid']>0){
            $pay_str = $pay_str."
支付方式：".$order['pay_name']."
支付金额：".$order['total_fee'];
        }
        if($order['surplus']>0){
            $pay_str = $pay_str."
使用余额：".$order['surplus'];
        }
        if($order['integral_money']>0){
            $pay_str = $pay_str."
使用积分：".$order['integral_money'];
        }
        if($order['bonus']>0){
            $pay_str = $pay_str."
使用红包：".$order['formated_bonus'];
        }



        if($order['pay_name']=="现金支付"||$order['paid_amount']>0){
            $pay_str = $pay_str."
实收金额：".$order['paid_amount']."  找零：".$order['change_amount'];
            if($refund_price>0) {
                $Surplus_price = $order['paid_amount'] - $order['change_amount'] - $refund_price;
                $pay_str = $pay_str . "
退款金额：" . $refund_price . "
剩余金额：" . $Surplus_price;
            }
        }else{
            if($refund_price>0){
                $Surplus_price = $order['total_fee'] - $refund_price;
                $pay_str = $pay_str."
退款金额：".$refund_price."
剩余金额：".$Surplus_price;
            }
        }

        $new_count = $order['total_fee'] - $order['refund_amount'] - $order['shipping_fee'];
        $market_fee_s = $order['total_fee'] - $order['refund_amount'] - $order['shipping_fee'] - $market_fee;

        $data["content"] = "天河区珠江新城花城汇北区UA影院旁
North area of MALL OF THE WORLD of Guangzhou Zhu Jiang New Town
编号：".$order['order_sn']."
日期：".date("Y-m-d")." ID:".$order['order_id']."
打单员：".$distribute_info['user_name']."
============商品信息============
".$goods_str."合计：    ".count($goods_list)."    ".$new_count.$refund_str."
============支付信息============
原价：".$market_fee." 优惠：".$market_fee_s."
运费：".$order['shipping_fee'].$pay_str."
下单日期：".$order['formated_add_time']."
============配送信息============
".$order['region_name']."
客户名称：".$order['consignee']."
联系电话：".$order['mobile']."
期望时间：".$order['best_time']."
客户备注：".$order['postscript']."
配送地址：".$order['address']."
================================
扫码关注食得鲜
抢低至5折元宵爆品
在线一键下单，还能为您送货上门
如需帮助请拨打全国服务热线：
400-3-8302-108
微店：w.shidexian.com";

//        echo $data["content"];
//        exit();


        returnApiSuccess($data,"已返回数据");
    }


    /**
     * 设置商品选中状态
     * rui poptser@foxmail.com 2016-10-21 14:43:47
     */
    // TODO 修改商品选中状态 set_select
    public function set_select(){
        $wp_userid=I('post.user_id','intval');  //用户ID
        $order_id     =I('post.order_id','intval');     //订单ID
        $goods_id     =I('post.goods_id','intval');     //商品ID
        if(empty($wp_userid)||empty($order_id)||empty($goods_id)){
            returnApiError('参数错误');
        }
        $this->check_user($wp_userid);

        $wid = $this->get_user_wid_identity($wp_userid);

        $selected = M("order_goods")->where("order_id =".$order_id." AND goods_id =".$goods_id)->getField("selected");
        if($selected==0){
            M("order_goods")->where("order_id =".$order_id." AND goods_id =".$goods_id)->setField("selected",1);
            $data['selected'] = 1;
        }else{
            M("order_goods")->where("order_id =".$order_id." AND goods_id =".$goods_id)->setField("selected",0);
            $data['selected'] = 0;
        }

        returnApiSuccess($data,"修改成功");
    }

    /**
     * 售后商品处理
     * rui poptser@foxmail.com 2016-10-12 10:44:05
     * handle_data goods_id type(1,2) number
     */
    // TODO 售后商品处理 handle_goods

    public function handle_goods(){
        //returnApiError("APP 退款功能修改中，如有需要请联系客服使用后台退款");
        $order_id = I('post.order_id','intval');    //订单号
        $user_id = I('post.user_id','intval');
        $this->check_user($user_id);    //检查用户
        $wid = $this->get_user_wid_identity($user_id);

        $update = I("post.handle_data");
        $update = str_replace('&quot;','"',$update);

        $url=C("SDX_SEND_DOMIANURL")."index.php?m=admin&c=Store&a=refund&api=skip";
        $param['order_id'] = $order_id;

        $paramsss = A("Distribution")->get_admin_user_name($user_id);
        $param['admin_user'] = $paramsss['user_name'].":".$paramsss['phone'];
//        echo json_encode($paramsss);
//        exit;


        $Json_Data = json_decode($update, true);
        if($Json_Data){
            //json 解析成功
            $order_info = M("order_info")->where("order_status !=2 AND order_id = ".$order_id." AND wid =".$wid." AND shipping_status = 3")->find();
            if($order_info){
                //订单状态正常，在配送中
                //查询此单商品剩余数量
                $sever_goods_list = $this->get_goods_list_real($order_id);

                //判断此有无提交数量超出实际商品剩余量的
//                foreach ($Json_Data as $key=>$value){
//                    $all_action = $value['lack']+$value['bad']+$value['back'];
//                    foreach ($sever_goods_list as $key2=>$value2){
//                        if($value['id']==$value2['goods_id']){
//                            if($value2['real_num']<$all_action){
//                                returnApiError("商品：".$value2['goods_name']."最大可操作数量为:".$value2['real_num']);
//                            }
//                        }
//                    }
//                }

                $lack_goods_list = array(); //缺货退款商品列表
                $bad_goods_list = array(); //次品退款商品列表
                $back_goods_list = array(); //退货退款商品列表


                $re_msg = null;
                foreach ($Json_Data as $key=>$value){

                    $goods_list= array();
                    $goods_info = M("order_goods")->field("goods_id,act_id,rec_id,goods_name,goods_price,goods_sn,goods_number")
                        ->where("order_id = ".$order_id." AND rec_id ='".$value['id']."'")->find();
                    $goods_list['goods_id'] = $goods_info['goods_id'];
                    $goods_list['rec_id'] = $goods_info['rec_id'];
                    $goods_list['act_id'] = $goods_info['act_id'];
                    $goods_list['goods_price'] = $goods_info['goods_price'];
                    $goods_list['goods_name'] = urlencode($goods_info['goods_name']);;
                    $goods_list['goods_sn'] = $goods_info['goods_sn'];
                    $goods_list['goods_number'] = $goods_info['goods_number'];

//                    dump($goods_list);
//                    exit();

                    if($value['lack']>0){
                        //加入缺货退款列表
                        $goods_list['cnt'] = $value['lack'];
                        array_push($lack_goods_list,$goods_list);
                        if($value['lack_remark']){
                            $refund_note_lack = $value['lack_remark'];
                        }
                    }
                    if($value['bad']>0){
                        //加入次品退款列表
                        $goods_list['cnt'] = $value['bad'];
                        $goods_list['cnt2'] = $value['bad'];
                        //dump($_FILES[$value['bad_photo']]['size']);
                        if($_FILES[$value['bad_photo_name']]['size']>100) {
                            $path = "uploads/refund_pic/" . rand(10000000, 99999999) . "." . end(explode('.', $_FILES[$value['bad_photo_name']]['name']));//接收文件目录
                            Ali_ossApi::upload($path, $_FILES[$value['bad_photo_name']]['tmp_name']);
                            $goods_list['photo'] = $path;
                        }
                        array_push($bad_goods_list,$goods_list);
                        if($value['bad_remark']){
                            $refund_note_bad = $value['bad_remark'];
                        }
                    }
                    if($value['back']>0){
                        //加入退款退款列表
                        $goods_list['cnt'] = $value['back'];
                        array_push($back_goods_list,$goods_list);
                        if($value['back_remark']){
                            $refund_note_back = $value['back_remark'];
                        }


                    }
                }
//                dump($bad_goods_list);
//                exit();

                //执行缺货退款操作
                if(count($lack_goods_list)>0){
                    $param['goods_list'] = json_encode($lack_goods_list);
                    $param['refund_type'] = '缺货退款';
                    $param['refund_amount'] = '';
                    $param['user_name'] = $param['admin_user'];
                    $param['refund_note'] = $refund_note_lack;
                    //dump($param);
                    //exit();
                    $lack_state = $this->rui_http_post($url,$param);
                    //dump($lack_state);
                    if(!$lack_state){
                        $re_msg=$re_msg."缺货退款 操作失败";
                    }
                }
                //执行次品退款操作
                if(count($bad_goods_list)>0){



                    $param['goods_list'] = json_encode($bad_goods_list);
                    $param['refund_type'] = '次品退款';
                    $param['refund_amount'] = '';
                    $param['user_name'] = $param['admin_user'];
                    $param['refund_note'] = $refund_note_bad;
                    $bad_state = $this->rui_http_post($url,$param);
                    if(!$bad_state){
                        $re_msg=$re_msg."次品退款 操作失败";
                    }
                }
                //执行退货退款操作
                if(count($back_goods_list)>0){
                    $param['goods_list'] = json_encode($back_goods_list);
                    $param['refund_type'] = '退货退款';
                    $param['refund_amount'] = '';
                    $param['user_name'] = $param['admin_user'];
                    $param['refund_note'] = $refund_note_back;
                    $back_state = $this->rui_http_post($url,$param);
                    //dump($back_state);
                    if(!$back_state){
                        $re_msg=$re_msg."退货退款 操作失败";
                    }
                }
                if($re_msg){
                    returnApiError("部分商品操作失败\n".$re_msg);
                }else{
                    returnApiSuccess(null,"退款成功");
                }
            }else{
                returnApiError("订单不存在/不在配货状态/非本仓库");
            }
        }else{
            returnApiError("数据组错误");
        }
    }

    /**
     * post 提交进行退款
     * @param $url
     * @param $param
     */
    private function rui_http_post($url, $param){
        $post_file=false;
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (is_string($param) || $post_file) {
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach($param as $key=>$val){
                $aPOST[] = $key."=".urlencode($val);
            }
            $strPOST =  join("&", $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($oCurl, CURLOPT_POST,true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            $res = json_decode($sContent,true);
            if($res['error']){
                return false;
            }else{
                return true;
            }
        }else{
            return false;
        }
    }
    /**
     * 根据订单ID获取订单里面的原始商品（未退款之前的）
     * rui
     * @param $order_id
     * @return mixed
     */
    private function get_goods_list_by_order($order_id,$no_gift=false){
        if($no_gift){
            $where['order_id'] = $order_id;
            $where['giving'] = array("neq",1);
            return M("order_goods")->where($where)->select();
        }else{
            return M("order_goods")->where(array("order_id"=>$order_id))->select();
        }

    }

    /**
     * 查询订单的退款商品记录
     * rui
     * @param $order_id
     * @return mixed
     */
    private function get_refund_goods_list($order_id){
        $refund_detail = M("refund_detail")->field("order_goods_id,sum(refund_number) as refund_number ,sum(surplus_number) as surplus_number,goods_id,goods_name,goods_sn ")->where(array("order_id"=>$order_id))->group('order_goods_id')->select();
        //dump(M("refund_detail")->getlastsql());
        return $refund_detail;
    }

    /**
     * TODO 获取订单内剩余商品数
     * rui
     * @param $order_id
     * @return mixed
     */
    public function get_goods_list_real($order_id,$no_gift =  false){
        $buy_goods_list = $this->get_goods_list_by_order($order_id,$no_gift);
        //dump($buy_goods_list);

        $refund_goods_list = $this->get_refund_goods_list($order_id);
        //dump($refund_goods_list);
//        exit();
        foreach ($buy_goods_list as $key=>$value){
            $buy_goods_list[$key]['cat_id'] = M("goods")->where(array("goods_id"=>$value['goods_id']))->getField('cat_id');
            $edit_goods = true;
            foreach ($refund_goods_list as $key2=>$value2){
                if($value['rec_id']==$value2['order_goods_id']){
                    $buy_goods_list[$key]['real_num'] = $value['goods_number']-$value2['refund_number'];
                    $edit_goods = false;
                }
            }
            if($edit_goods){
                $buy_goods_list[$key]['real_num'] = $value['goods_number'];
            }
            if($buy_goods_list[$key]['real_num']==0){
                unset($buy_goods_list[$key]);
            }
        }
        //dump($buy_goods_list);
        //echo "ddddddddd";
        //exit();
        return $buy_goods_list;
    }


    /**
     * TODO 获取预警URl  web
     * rui
     *
     */
    public function get_warn_url(){
        $data['url'] = C("SDX_SEND_DOMIANURL")."admin/customer_service.php?act=main&app_action=1";
        returnApiSuccess($data,"已返回数据");
    }


    /**
     * TODO 直接获取订单详情页 web
     * rui
     */
    public function get_order_web(){
        $order_id = $_POST['order_id'];
        $order_num = $_POST['order_num'];
        if(!empty($order_num)){
            //订单号不为空，根据订单号获取订单ID
            $order_id = M("order_info")->where("order_sn like '%".$order_num."%'")->getField('order_id');
        }
        if(!empty($order_id)){
            $data['url'] = C("SDX_SEND_DOMIANURL")."admin/order.php?act=info&order_id=".$order_id."&app_action=1";
            returnApiSuccess($data,"已返回数据");
        }else{
            returnApiError("订单ID为空");
        }
    }

    /**
     * todo 获取未出仓/应回仓订单概览信息
     * rui
     */
    public function un_outgo_survey(){
        $action = $_POST['action'];   //操作类型（1 未出仓  2应回仓）
        $user_id = $_POST['user_id'];   //操作类型（1 未出仓  2应回仓）

        $wData = M("zoning_cate")->field("id,name")->select();
        foreach ($wData as $key=>$value){
            $wdrlist = M("warehouse_deliver_region")->where(array("zoning_id"=>$value['id']))->getField("id",true);
            if(count($wdrlist)>0){
                $wData[$key]['wData'] = implode(",",$wdrlist);
            }
        }
        //dump($wData);
        $where['order_status'] = array("neq",2);    //订单未取消
        $where['pay_status'] = array("in","2,3");   //支付状态为已支付/部分退款
        $where['wid'] = $this->get_user_wid_identity($user_id);   //仓库ID
        if($action==1){
            $where['sorting_id'] = array("neq",0);      //已有配送员
            $where['shipping_status'] = 5;              //订单状态为已完成配货
            $where['outgo'] = 0;    //未出仓
        }elseif($action==2){
            $where['outgo'] = 2;    //应回仓
        }else{
            returnApiError("未知操作");
        }
        $re_data = array();
        foreach ($wData as $wKey=>$wValue) {
            if(empty($wValue['wData'])){
                continue;
            }
            $where['wdr_id'] = array("in",$wValue['wData']);
            $order_num = M('order_info')->where($where)->count();
            if($order_num>0){
                $one_data = array(
                    "id" => $wValue['id'],
                    "name" => $wValue['name'],
                    "num" => $order_num,
                );
                array_push($re_data,$one_data);
            }
        }
        if(empty($re_data)){
            returnApiError("无数据");
        }else{
            $data['list_area'] = $re_data;
            returnApiSuccess($data,"已返回数据");
        }
    }

    /**
     * todo 根据区域获取未出库/应回库订单组
     * rui
     */
    public function un_outgo(){
        $action = $_POST['action'];   //操作类型（1 未出仓  2应回仓）
        $area_id = $_POST['area_id'];   //仓库区域ID
        $user_id = $_POST['user_id'];   //
        if(!is_numeric($area_id)){
            returnApiError("区域ID错误");
        }
        $wdrlist = M("warehouse_deliver_region")->where(array("zoning_id"=>$area_id))->getField("id",true);
        if(count($wdrlist)>0){
            $wdr_id = implode(",",$wdrlist);
        }else{
            returnApiError("此大区未关联配送区域");
        }
        $where['wdr_id'] = array("in",$wdr_id);
        $where['order_status'] = array("neq",2);    //订单未取消
        $where['pay_status'] = array("in","2,3");   //支付状态为已支付/部分退款
        $where['wid'] = $this->get_user_wid_identity($user_id);   //仓库ID
        if($action==1){
            $where['sorting_id'] = array("neq",0);      //已有配送员
            $where['outgo'] = 0;    //未出仓
            $where['shipping_status'] = 5;              //订单状态为已完成配货
        }elseif($action==2){
            $where['outgo'] = 2;    //应回仓
            $where['shipping_status'] = 0;              //订单状态为未发货状态
        }else{
            returnApiError("未知操作");
        }

        $data['list'] =$list= M("order_info")->field('order_id,order_sn')->where($where)->order('order_id desc')->select();
        if(count($list)>0){
            returnApiSuccess($data,"已经返回数据");
        }else{
            returnApiError("(～￣▽￣)～没有找到记录");
        }
    }

    /**
     * todo 出仓/回仓 操作
     * rui
     */
    public function outgo_action(){
        $action      = $_POST['action'];        //操作类型（1 未出仓  2应回仓）
        $user_id     = $_POST['user_id'];       //用户ID
        $order_str = $_POST['order_array'];     //订单ID组，多个以，号分割
        $driver_name = $_POST['driver_name'];   //司机姓名
        $car_sn = $_POST['car_sn'];             //车牌号
        $go_time = $_POST['go_time'];           //出发司机
        $to_time = $_POST['to_time'];           //预期到达司机
        if($action==1){
            if(empty($driver_name)||empty($car_sn)|empty($go_time)||empty($to_time)){
                returnApiError("部分数据为空");
            }
        }


        $order_array = explode(",",$order_str);
        array_filter($order_array);
        $where['order_status'] = array("neq",2);    //订单未取消
        $where['pay_status'] = array("in","2,3");   //支付状态为已支付/部分退款
        $where['wid'] = $this->get_user_wid_identity($user_id);   //仓库ID
        if($action==1){
            //未出仓
            $where['shipping_status'] = 5;
            $where['outgo'] = 0;
            $data['outgo'] =  1;
            $action = "订单已出仓<br/>司机:".$driver_name." 车牌号:".$car_sn." 出发时间:".$go_time." 预期到达时间:".$to_time;
        }elseif($action==2){
            $where['outgo'] = 2;    //应回仓
            $data['outgo'] =  0;
            $data['shipping_status'] =  0;
            $action = "订单已回仓";
        }else{
            returnApiError("未知操作");
        }

        if(count($order_array)>0){
            $i=0;
            foreach ($order_array as $key=>$value){
                $where['order_id'] = $value;
                $order_info = M("order_info")->where($where)->find();
                $Result = M("order_info")->where($where)->save($data);
                if($Result){
                    $i++;
                    $a=array(
                        'order_id'=>$value,
                        'user_id'=>$user_id,
                        'order_status'=>$order_info['order_status'],
                        'shipping_status'=>$order_info['shipping_status'],
                        'pay_status'=>$order_info['pay_status'],
                        'action_note'=>$action
                    );
                    A("Distribution")->record_diliveryman_log($a);//记录配送员操作日志
                }
            }
            returnApiSuccess(null,"一共".count($order_array)."个订单\n成功:".$i);
        }else{
            returnApiError("老板，勾选订单先");
        }
    }

    public function test(){
        dump($_FILES['/sdcard/shidexian/20170110073133.jpg']['size']);
        $path= "uploads/refund_pic/".rand(10000000,99999999).".".end(explode('.', $_FILES['/sdcard/shidexian/20170110073133.jpg']['name']));//接收文件目录
        //$pic_name = rand(10000000,99999999).".jpg";
        //$image = new \Think\Image();
        //$image->open($_FILES['takeCardPic']['tmp_name'])->text('shidexian.com','./DymoFontInvers.ttf',20,'#FFFFFF',\Think\Image::IMAGE_WATER_SOUTHEAST)->save("cache/".$pic_name);
        Ali_ossApi::upload($path, $_FILES['/sdcard/shidexian/20170110073133.jpg']['tmp_name']);
    }

}